package baidu.hudson.plugin.result.collector.CCheckExtend;

import baidu.hudson.plugin.result.collector.utils.JsonUtils;
import hudson.model.AbstractBuild;
import org.codehaus.jackson.JsonGenerationException;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.EnumMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Richard
 * Date: 4/24/11
 * Time: 12:44 AM
 * To change this template use File | Settings | File Templates.
 */
public class InformationAbstractor {
    private Object ccheckObject;

    public InformationAbstractor(AbstractBuild build, String actionClassToken) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        for (int i = 0; i < build.getActions().size(); i++) {
            String className = "";
            if (build.getActions().get(i).getClass().toString().contains(actionClassToken)) {
                Method method = build.getActions().get(i).getClass().getMethod("getResult");
                ccheckObject = method.invoke(build.getActions().get(i));
            }
        }
    }

    private <T> T getAtrrribute(CCheckMethodEnum attri , T type) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method ccheckObjectMethod = ccheckObject.getClass().getMethod(attri.getMethodName());
        return (T) ccheckObjectMethod.invoke(ccheckObject);
    }

    public EnumMap<CCheckMethodEnum , String> generateCCheckResultMap() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, InstantiationException {
        EnumMap<CCheckMethodEnum , String> results = new EnumMap<CCheckMethodEnum,String>(CCheckMethodEnum.class);
       for(CCheckMethodEnum method : CCheckMethodEnum.values()){
           String value;
           if(method.equals(CCheckMethodEnum.GetScore)) {
               value = String.valueOf(getAtrrribute(method,new Float(0)));
           }
           else{
              value = getAtrrribute(method,new String());
           }
             results.put(method,value);
       }
        return results;
    }

}
